package com.xxwy.simple.rpc.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import	java.util.concurrent.Executors;

import java.util.concurrent.ExecutorService;

/**
 * @author wy
 * @date 2020/3/9 10:51
 */
public class NettyClient {

  private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

  private static NettyClientHandler clientHandler;

  public Object getBean(final  Class<?> serverClass,final String providerName){
    return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
        new Class<?>[]{serverClass},(proxy, method, args)->{
      if(clientHandler == null){
        System.out.println("错误，没有启动client");
        return null;
      }
      clientHandler.setPara(providerName+args[0]);
      return executorService.submit(clientHandler).get();
    });

  }

  public static void start(String hostname,int port){
    start0(hostname,port);
  }

  private static void start0(String hostname,int port){
    clientHandler = new NettyClientHandler();
    NioEventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(
            new ChannelInitializer<SocketChannel>() {
              @Override
              protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(clientHandler);
              }
            }
        );

    try {
      bootstrap.connect(hostname, port).sync();

      //没有关？
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}
